﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Cut
{
    public class Material : Size, ISizes
    {
        public byte[,] FillingMatrix { private set; get; }
        public List<Detail> Details { private set; get; }

        public int GetSquare()
        {
            return Width * Height;
        }

        public int GetSquareByBlock(Detail detail)
        {
            return (Width / detail.GetWidth()) * (Height / detail.GetHeight());
        }

        public Material(int width, int height, List<Detail> details)
        {
            Width = width;
            Height = height;
            Details = details;
        }

        public void CreateFillingMatrix(Detail detail)
        {
            var nWidth = Width / detail.GetWidth();
            var nHeight = Height / detail.GetHeight();
            FillingMatrix = new byte[nHeight, nWidth];
        }

        public void AddDetails(List<Detail> tempDetails)
        {
            tempDetails.Sort();
            foreach (var item in tempDetails.Where(item => item.GetSquare() < GetSquare()))
            {
                for (var i = 0; i < FillingMatrix.GetLength(0); i++)
                {
                    for (var j = 0; j < FillingMatrix.GetLength(1); j++)
                    {
                        if (FillingMatrix.GetLength(0) - i > item.GetWidth() &&
                            FillingMatrix.GetLength(1) - j > item.GetHeight())
                        {
                            CheckIsPlaceable(item, i, j);
                        }
                    }
                }
            }
        }

        private bool CheckIsPlaceable(Detail detail, int rowIndex, int colIndex)
        {
            for (var i = 0; i < rowIndex; i++)
            {
                for (var j = 0; j < colIndex; j++)
                {
                    if (FillingMatrix[i, j] != 0)
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
